﻿using System.IO;
using System;
using System.Collections.Generic;

using System.Text;

namespace xReplace
{
    class StoreCommand : AbstractProcessingCommand
    {
        public StoreCommand(ref Content pipes)
            : base(ref pipes)
        {}

        public override bool ProcessCommand(System.Xml.XmlNodeList param)
        {
            string startsWith = GetNodeValue("startswith", param);
            string endsWith = GetNodeValue("endswith", param);
            string toLabel = this.GetNodeValue("tolabel", param);
            string fromLabel = this.GetNodeValue("fromlabel", param);
            string filename = this.GetNodeValue("filename", param);
            string renameRules = this.GetNodeValue("renamerules", param);

            string txt = this.GetNodeValue("value", param);
            
            string skipStart = GetNodeValue("skipstart", param);
            string skipEnd = GetNodeValue("skipend", param);

            if (GetNodeAttributeAsBoolean("startswith", "escape", param))
                startsWith = SpecialCharHelper.Unescape(startsWith);
            if (GetNodeAttributeAsBoolean("endswith", "escape", param))
                endsWith = SpecialCharHelper.Unescape(endsWith);
            if (GetNodeAttributeAsBoolean("skipstart", "escape", param))
                skipStart = SpecialCharHelper.Unescape(skipStart);
            if (GetNodeAttributeAsBoolean("skipend", "escape", param))
                skipEnd = SpecialCharHelper.Unescape(skipEnd);
            if (GetNodeAttributeAsBoolean("value", "escape", param))
                txt = SpecialCharHelper.Unescape(txt);


            string ignoreCaseStr = GetNodeValue("ignorecase", param);
            bool ignoreCase = (ignoreCaseStr.ToLower() == "true") ? true : false;

            string tmp = "";
            if ((fromLabel != "") && (this.NodeExists("fromlabel",param)))
                tmp = this.contentPipelines.LoadContent(fromLabel);
            else if ((filename != "") && (this.NodeExists("filename", param)))
            {
                if (renameRules != "")
                    filename = RenameHelper.PerformRename(filename, renameRules, this.contentPipelines);
                tmp = File.ReadAllText(filename);
            }
            else if ((txt != "") && (this.NodeExists("value", param)))
                tmp = txt;
            else
                tmp = this.contentPipelines.DefaultContent;

            TextFragment frag = new TextFragment(tmp);
            frag.GrabFragment(startsWith, endsWith, skipStart, skipEnd, ignoreCase);
            this.contentPipelines.StoreContent(toLabel, frag.Fragment);
            return true;
        }

    }
}
